package com.web.security.provider;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.web.adm.entity.AdminEntity;
import com.web.security.service.SecurityService;
import com.web.security.user.WebUser;


@Service
public class DaoUserDetails implements UserDetailsService{
	@Autowired
	private SecurityService securityService;
	
	private static final Logger LOGGER = Logger.getLogger(DaoUserDetails.class);
			
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {

		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;
		LOGGER.info("===================== Step UserDetails");
		GrantedAuthority[] authorities = {new GrantedAuthorityImpl("ROLE_USER")};
		if(username.equals("") || username == null){
			throw new BadCredentialsException("Wrong username or password");
		}else{
			
			AdminEntity admUser = securityService.getUser(username);
			if(admUser == null){
				throw new BadCredentialsException("Wrong username or password");
			}
			
			return new WebUser(admUser.getUserID(), admUser.getUserPassword(), enabled,
					accountNonExpired, credentialsNonExpired,
					accountNonLocked, authorities);
			
		}
	}
}
